import {AxdrType} from "./AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {AxdrLength} from "./AxdrLength";



export class AxdrOctetString implements AxdrType{

    octetString : Buffer | null = null;
    length : number = 0;

    constructor() {

    }

    set_length(length : number){
        this.length = length;
        this.octetString = Buffer.alloc(length);
    }

    set_dataCode(octetString : Buffer){
        if(octetString != null){
            this.octetString = octetString;
        }
    }

    set_all(length : number, octetString : Buffer){
        if(length != 0 && length != octetString.length){
            throw new Error("octetString of wrong size");
        }
        this.length = length;
        this.octetString = octetString;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;
        let len = this.length;
        if(len == 0){
            let l = new AxdrLength(0);
            codeLength += l.decode(input);
            len = l.getValue();
            this.octetString = Buffer.alloc(len);
        }
        if (len != 0) {
            if (input.readoffset(this.octetString, 0, len) < len) {
                throw new Error("Error Decoding AxdrOctetString");
            }
            codeLength += len;
        }
        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {

        let codeLength;
        if(this.octetString != null){
            output.writeByte(this.octetString);
            codeLength = this.octetString.length;

            if(this.length == 0){
                let length = new AxdrLength(this.octetString.length);
                codeLength += length.encode(output)
            }
        }

        return codeLength;
    }

    getValue() : Buffer{
        return this.octetString;
    }

    toString() : string{
        let s = ""
        for (let i = 0; i < this.octetString.length; i++) {
            let hexString = (this.octetString[i] & 0xff).toString(16);
            if (hexString.length == 1) {
                s += '0';
            }
            s += hexString;
        }
        return s;
    }

}
